const {
  readFileSync,
  writeFileSync
} = require('fs');
const {
  resolve
} = require('path');

//导入自定义面向AOP的轮子
require('./Function');

function readFile(path) {
  console.log('调试：执行顺序7');

  return readFileSync(resolve(__dirname, path), 'utf8');
}

function writeFile(path, data) {
  console.log('调试：执行顺序12');
  writeFileSync(resolve(__dirname, path), JSON.stringify(data));
}

//fn -> 用户定义的函数里面是业务逻辑程序 -> main
function fileOperation(path, fn) {
  console.log('调试：执行顺序1');

  return fn.before(() => {
      console.log('调试：执行顺序6');

      //读取文件
      return JSON.parse(readFile(path) || '[]');
    })
    .after((data) => {
      console.log('修改文件内容');
      console.log('调试：执行顺序11');
      //这里data是用户定义函数执行后返回的结果
      // console.log(data);
      //删除后的todoList

      writeFile(path, data);
      console.log('文件写入完毕');

      //返回删除后的data数据
      return data;
    })();
}

module.exports = {
  fileOperation
}